import 'dart:io';
import 'dart:ui';
import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  //设置状态栏颜色
  SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.red, //状态栏背景颜色
      statusBarIconBrightness: Brightness.light //状态栏字体颜色
      ));

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        //隐藏DEBUG图标
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
          useMaterial3: true,
        ),
        home: const Scaffold(
          body: MyHomePage(),
        ));
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _picker = ImagePicker();
  File? _file;
  GlobalKey globalKey = GlobalKey();
  List list = [
    "images/a1.png",
    "images/a2.png",
    "images/a3.png",
    "images/a4.png",
    "images/a5.png",
    "images/a6.png",
    "images/a7.png",
  ];
  int num = 0;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      height: double.infinity,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          //要生成图片组件用RepaintBoundary包裹
          RepaintBoundary(
            key: globalKey,
            child: Stack(
              children: [
                if (_file != null)
                  Stack(
                    children: [
                      Image.file(
                        _file!,
                        width: 200,
                        height: 200,
                        fit: BoxFit.cover,
                      ),
                    ],
                  )
                else
                  Stack(
                    children: [
                      Image.asset(
                        "images/a.png",
                        width: 200,
                        height: 200,
                        fit: BoxFit.cover,
                      ),
                    ],
                  ),
                Image.asset(
                  list[num],
                  width: 200,
                  height: 200,
                  fit: BoxFit.cover,
                ),
              ],
            ),
          ),
          ElevatedButton(
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(Colors.red),
            ),
            onPressed: () async {
              var xfile = await _picker.pickImage(
                  source: ImageSource.gallery,
                  //宽高设置过小影响图片显示清晰度
                  maxWidth: 1000,
                  maxHeight: 1000,
                  requestFullMetadata: false);
              if (xfile != null) {
                setState(() {
                  _file = File(xfile.path);
                });
              }
            },
            child: const Text(
              '从相册中选择头像',
              style: TextStyle(color: Colors.white),
            ),
          ),
          ElevatedButton(
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(Colors.red),
            ),
            onPressed: () {
              saveImage(globalKey);
            },
            child: const Text(
              '保存合成头像',
              style: TextStyle(color: Colors.white),
            ),
          ),
          ElevatedButton(
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(Colors.red),
            ),
            onPressed: () {
              setState(() {
                num++;
                if (num >= list.length) {
                  num = 0;
                }
              });
            },
            child: const Text(
              '换个头像框',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }

  /// 保存图片
  Future<void> saveImage(GlobalKey globalKey) async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    String osVersion = androidInfo.version.release;
    RegExp regExp = RegExp(r"(\d+)");
    Match match = regExp.firstMatch(osVersion) as Match;
    String? version = match.group(0);
    int targetVersion = 13;
    if (int.parse(version!) >= targetVersion) {
      //系统大于等于13
      //检查是否有存储权限
      var status = await Permission.photos.status;
      if (!status.isGranted) {
        status = await Permission.photos.request();
        return;
      }
    } else {
      //系统小于13
      //检查是否有存储权限
      var status = await Permission.storage.status;
      if (!status.isGranted) {
        status = await Permission.storage.request();
        return;
      }
    }

    RenderRepaintBoundary boundary =
        globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    var image = await boundary.toImage(pixelRatio: 5.0);
    ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
    final pngBytes = byteData!.buffer.asUint8List();
    await ImageGallerySaver.saveImage(pngBytes);
    _alertDialog();
  }

  ///AlertDialog确认取消弹窗
  void _alertDialog() {
    showDialog(
      context: context,
      barrierDismissible: true, //点击弹窗以外背景是否取消弹窗
      builder: (context) {
        return AlertDialog(
          title: const Text("温馨提示"),
          content: const Text("图片保存成功，请到相册查看！"),
          actions: [
            TextButton(
              onPressed: () {
                //关闭弹窗
                Navigator.of(context).pop();
              },
              child: const Text("晓得了，退下吧"),
            ),
          ],
        );
      },
    );
  }
}
